﻿using System.Collections.Generic;
using Codemonk.Common.Emit;

namespace Codemonk.Soya
{
    public sealed class ObjectFiller : IObjectFiller
    {
        public IEnumerable<T> Fill<T>(List<IDictionary<string, object>> data) where T : new()
        {
            foreach (var item in data)
            {
                yield return Fill<T>(item);
            }
        }

        private TypeAccessorFactory factory = new TypeAccessorFactory();

        private T Fill<T>(IDictionary<string, object> data) where T : new()
        {
            if (data == null) return default(T);
            T result = new T();
            var accessor = factory.GetByType(typeof(T));
            foreach (var item in data)
            {
                try
                {
                    accessor.SetProperty(result, item.Key.ToUpper(), item.Value);
                }
                catch { }
            }
            return result;
        }
    }
}
